package com.hs.telepass.crash;

import android.os.Environment;
import com.hs.telepass.utils.SDCardUtil;

import java.io.*;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CrashHandler implements UncaughtExceptionHandler {
	public static void start() {
		// 设置异常处理实例
		CrashHandler handler = new CrashHandler();
		Thread.setDefaultUncaughtExceptionHandler(handler);
	}

	// 系统默认的UncaughtException处理
	private Thread.UncaughtExceptionHandler mDefaultHandler;

	public CrashHandler() {
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		try {
			// 创建日志文件
			File file = createCreashLogFile();

			// 写入日志文件
			if (file != null && file.exists()) {
				writeLog(file, ex);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 将异常抛给系统处理
		mDefaultHandler.uncaughtException(thread, ex);
	}

	private void writeLog(File logFile, Throwable ex) {
		PrintStream printStream = null;
		FileOutputStream fos = null;

		// 写入日志文件
		try {
			fos = new FileOutputStream(logFile);
			printStream = new PrintStream(fos);
			ex.printStackTrace(printStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeQuietly(printStream);
			closeQuietly(fos);
		}
	}

	private void closeQuietly(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** 创建一个空白的崩溃日志文件 */
	public static File createCreashLogFile() throws IOException {
		if (!isExternalStorageAvaliable()) { // 检查存储是否可用
			return null;
		}

		File directory = SDCardUtil.getCrashDirectory();
		File file = new File(directory, createCrashLogFileName());
		if (file.exists()) {
			boolean isDeleteSucceed = file.delete();
			if (!isDeleteSucceed) {
			    return null;
			}
		}
		boolean isCreateSucceed = file.createNewFile();

		if (isCreateSucceed) {
		    return file;
		} else {
		    return null;
		}
	}

	/** 存储是否可用 */
	public static boolean isExternalStorageAvaliable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else {
			return false;
		}
	}

	private static String createCrashLogFileName() {
		String dateString = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		return "CrashLog_" + dateString + ".txt";
	}
}